<template>
  <div class="excel-preview">
    <div v-if="loading" class="loading-container">
      <el-icon class="is-loading" :size="50">
        <Loading />
      </el-icon>
      <p>Excel 表格加载中...</p>
    </div>

    <div v-else-if="error" class="error-container">
      <el-icon :size="80">
        <WarningFilled />
      </el-icon>
      <p>{{ error }}</p>
    </div>

    <div v-else class="excel-container">
      <!-- Sheet 标签页 -->
      <el-tabs v-model="activeSheet" class="sheet-tabs">
        <el-tab-pane
          v-for="sheetName in sheetNames"
          :key="sheetName"
          :label="sheetName"
          :name="sheetName"
        >
          <el-scrollbar>
            <div class="table-container">
              <table class="excel-table">
                <tbody>
                  <tr v-for="(row, rowIndex) in sheets[sheetName]" :key="rowIndex">
                    <td v-for="(cell, colIndex) in row" :key="colIndex">
                      {{ cell }}
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </el-scrollbar>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import * as XLSX from 'xlsx'
import { Loading, WarningFilled } from '@element-plus/icons-vue'

const props = defineProps({
  file: {
    type: Object,
    required: true
  }
})

const loading = ref(false)
const error = ref('')
const sheets = ref({})
const sheetNames = ref([])
const activeSheet = ref('')

// 加载 Excel 文件
const loadExcel = async () => {
  try {
    loading.value = true
    error.value = ''
    sheets.value = {}
    sheetNames.value = []

    // 读取文件
    let arrayBuffer
    
    if (props.file.isUrl) {
      console.log('✓ 使用 URL 加载 Excel:', props.file.url)
      const response = await fetch(props.file.url)
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`)
      }
      arrayBuffer = await response.arrayBuffer()
    } else {
      console.log('✓ 使用本地文件加载 Excel')
      arrayBuffer = await props.file.raw.arrayBuffer()
    }
    
    // 解析 Excel
    const workbook = XLSX.read(arrayBuffer, { type: 'array' })
    
    // 获取所有 sheet 名称
    sheetNames.value = workbook.SheetNames
    
    // 解析每个 sheet
    workbook.SheetNames.forEach(sheetName => {
      const worksheet = workbook.Sheets[sheetName]
      // 转换为 2D 数组
      const data = XLSX.utils.sheet_to_json(worksheet, { 
        header: 1,
        defval: '',
        blankrows: true
      })
      sheets.value[sheetName] = data
    })

    // 设置默认激活的 sheet
    if (sheetNames.value.length > 0) {
      activeSheet.value = sheetNames.value[0]
    }

    loading.value = false
  } catch (err) {
    console.error('Excel 加载失败:', err)
    if (err.message.includes('CORS') || err.message.includes('Failed to fetch')) {
      error.value = 'Excel 加载失败：CORS 跨域限制。建议：1) 下载后上传 2) 使用代理 URL'
    } else {
      error.value = 'Excel 文件加载失败：' + err.message
    }
    loading.value = false
  }
}

watch(() => props.file, () => {
  if (props.file) {
    loadExcel()
  }
}, { immediate: true })

onMounted(() => {
  if (props.file) {
    loadExcel()
  }
})
</script>

<style scoped>
.excel-preview {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #ffffff;
}

.loading-container,
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #409EFF;
}

.error-container {
  color: #F56C6C;
}

.loading-container p,
.error-container p {
  margin-top: 16px;
  font-size: 14px;
}

.excel-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.sheet-tabs {
  flex: 1;
  display: flex;
  flex-direction: column;
}

:deep(.el-tabs__content) {
  flex: 1;
  overflow: hidden;
}

:deep(.el-tab-pane) {
  height: 100%;
}

.table-container {
  padding: 20px;
  min-width: max-content;
}

.excel-table {
  border-collapse: collapse;
  font-size: 13px;
  background: white;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.excel-table td {
  border: 1px solid #e4e7ed;
  padding: 8px 12px;
  min-width: 80px;
  white-space: nowrap;
}

.excel-table tr:first-child td {
  background: #f5f7fa;
  font-weight: 600;
  color: #303133;
}

.excel-table tr:hover td {
  background: #fafafa;
}
</style>

